'use strict';
const Controller = require('egg').Controller;
// o2DLz0iyY2djgSGFQj-CbnuGISqM
// _QFX20pNRvXV1T142o6iePwDKsieQ5R7r6YlNmSHXKs
module.exports = class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    const { openid, signature, timestamp, nonce } = ctx.query;
    // 解签
    const sign = ctx.service.wxCrypt.getSignature(timestamp, nonce);
    // 获取XML
    const xml = await ctx.service.wxCrypt.getXml(ctx.req);
    // 解析XML => jSON
    const result = await ctx.service.wxCrypt.parseXML(xml);
    const { ToUserName } = result;
    // 验证签名 得到返回的XML
    const msg = signature === sign ? `<xml>
    <ToUserName><![CDATA[${openid}]]></ToUserName>
    <FromUserName><![CDATA[${ToUserName}]]></FromUserName>
    <CreateTime>${new Date().getTime()}</CreateTime>
    <MsgType><![CDATA[transfer_customer_service]]></MsgType>
    </xml>` : '';
    // 解密 文本信息
    const data = await ctx.service.wxCrypt.decryptMsg(ctx.query, result);
    console.log(data);
    if (data.Content === '萌岛技术部灿灿') {
      console.log(data.Content)
      await ctx.service.mail.sent('萌岛技术部灿灿', data.FromUserName);
    }
    ctx.res.setHeader('Content-Type', 'application/xml');
    ctx.body = msg;
  }

  async test() {
    const { ctx } = this;
    this.ctx.body = ctx.query.echostr;
  }
  async orderCancellation() {
    const { ctx } = this;
    // const msg = await ctx.service.weChat.getTemplate(ctx.query);
    const data = await ctx.service.weChat.orderCancellation(ctx.query);
    ctx.body = data;
  }
  async deliverGoods() {
    const { ctx } = this;
    console.log('deliverGoods');
    // const msg = await ctx.service.weChat.getTemplate(ctx.query);
    const data = await ctx.service.weChat.deliverGoods(ctx.query);
    ctx.body = data;
  }
};

